package com.example.wiki.service.impl;

import com.example.wiki.common.util.CopyUtil;
import com.example.wiki.common.vo.PageVo;
import com.example.wiki.entity.Category;
import com.example.wiki.entity.CategoryExample;
import com.example.wiki.mapper.CategoryMapper;
import com.example.wiki.req.CategoryQueryReq;
import com.example.wiki.req.CategorySaveReq;
import com.example.wiki.service.CategoryService;
import com.example.wiki.util.SnowFlake;
import com.example.wiki.vo.CategoryVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SnowFlake snowFlake;//使用雪花算法生成id

    @Override
    public  PageVo<CategoryVo> list(CategoryQueryReq categoryQueryReq) {
        //组装sql
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        CategoryExample.Criteria criteria = categoryExample.createCriteria();

        //分页查询
        PageHelper.startPage(categoryQueryReq.getPage(), categoryQueryReq.getSize());
        List<Category> list = categoryMapper.selectByExample(categoryExample);

        //处理数据后封装
        PageInfo<Category> pageInfo = new PageInfo<>(list);
        List<CategoryVo> categoryVoList = CopyUtil.copyList(list, CategoryVo.class);
        PageVo<CategoryVo> pageVo =new PageVo<CategoryVo>();
        pageVo.setList(categoryVoList);
        pageVo.setTotal(pageInfo.getTotal());
        return pageVo;
    }

    @Override
    public  List<CategoryVo> all() {
        //组装sql
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        List<CategoryVo> categoryVoList = CopyUtil.copyList(categoryList, CategoryVo.class);

        return categoryVoList;
    }

    @Override
    public void save(CategorySaveReq categorySaveReq) {
        Category category =CopyUtil.copy(categorySaveReq,Category.class);
        System.out.println(category);
        if(category.getId() ==null  ||  StringUtil.isEmpty(category.getId().toString())){
            category.setId(snowFlake.nextId());
            category.setParenet(ObjectUtils.isEmpty(categorySaveReq.getParenet())? 0 : categorySaveReq.getParenet());
            categoryMapper.insert(category);
        }else{
            categoryMapper.updateByPrimaryKeySelective(category);
        }
    }

    @Override
    public void remove(Long id) {
        if (id != null){
            categoryMapper.deleteByPrimaryKey(id);
        }
    }
}
